#include <boost/bind.hpp>

#include "NetworkManager.hh"

NetworkManager::NetworkManager(int port) : mPort(port),
					   mEndPoint(boost::asio::ip::tcp::v4(), mPort),
					   mAcceptor(mService, mEndPoint)
{
  this->waitForSession();
}

NetworkManager::~NetworkManager(void)
{
  ;
}

void					NetworkManager::waitForSession(void)
{
  boost::shared_ptr<NetworkSession>	session = boost::shared_ptr<NetworkSession>(new NetworkSession(mService, mCallbackReceive));
  
  mAcceptor.async_accept(session->getSocket(),
			 boost::bind(&NetworkManager::handleAccept, this, 
				     boost::asio::placeholders::error,
				     session));
}

void					NetworkManager::handleAccept(const boost::system::error_code & error, boost::shared_ptr<NetworkSession> session)
{
  mSessions.push_back(session);
  session->receive();
  this->waitForSession();
}

void					NetworkManager::run(void)
{
  mService.run();
}

void					NetworkManager::setCallbackAccept(const boost::function<void(NetworkSession &)> callbackAccept)
{
  mCallbackAccept = callbackAccept;
}

void					NetworkManager::setCallbackReceive(const boost::function<void(NetworkSession &, void *, size_t)> callbackReceive)
{
  mCallbackReceive = callbackReceive;
}
